package www.dashu.com.controller;

import www.dashu.com.api.CommonResult;
import www.dashu.com.service.RedisService;
import www.dashu.com.domain.*;
import www.dashu.com.dto.UserQuery;
import www.dashu.com.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 后台用户管理
 */
@Controller
@Api(tags = "SysUserController", description = "用户管理")
@RequestMapping("/user")
public class SysUserController
{

    @Autowired
    SysUserService userService;

    @Autowired
    RedisService redisService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    SysUserRoleService userRoleService;

    @Autowired
    SysPermissionService permissionService;

    @Autowired
    SysRoleService roleService;

    @Autowired
    SysAppService appService;

    @Autowired
    SysUserAppService userAppService;

    @ApiOperation(value = "用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Page<SysUser>> list(UserQuery userQuery) {

        try {
            Page<SysUser> pageData = userService.findAll(userQuery);
            return CommonResult.success(pageData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @ApiOperation(value = "新增用户")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@RequestBody SysUser user) {
        user.setId(userService.createId(user));
        user.setPassword(passwordEncoder.encode("123456"));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userService.save(user);
        return CommonResult.success();
    }

    @ApiOperation(value = "修改用户")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@RequestBody SysUser user) {
        user.setUpdateTime(new Date());
        user.setPassword(null);
        userService.save(user);
        return CommonResult.success();
    }

    @ApiOperation(value = "删除用户")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult delete(@RequestBody SysUser user) {
        userService.deleteById(user.getId());
        userRoleService.deleteUserRoleByUserId(user.getId());
        return CommonResult.success();
    }

    @ApiOperation(value = "更新用户角色")
    @RequestMapping(value = "/roleUpdate", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult roleUpdate(@RequestBody SysUser user) {
        userRoleService.deleteUserRoleByUserId(user.getId());
        List<SysUserRole> list = new ArrayList<>();
        for(String rid : user.getRoles()){
            SysUserRole userRole = new SysUserRole();
            userRole.setId(userRoleService.createId(userRole));
            userRole.setUId(user.getId());
            userRole.setRId(Long.parseLong(rid));
            userRole.setCreateTime(new Date());
            userRole.setUpdateTime(new Date());
            list.add(userRole);
        }
        userRoleService.saveAll(list);
        permissionService.initResourceRolesMap();
        return CommonResult.success();
    }

    @ApiOperation(value = "获取用户角色")
    @RequestMapping(value = "/roleList", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult<Map<String,Object>> roleList(@RequestBody SysUser user) {
        Map<String,Object> ret = new HashMap<>();
        List<SysRole> roles = roleService.findAll();
        List<SysUserRole> userRoles = userRoleService.findUserRolesByUserId(user.getId());
        List<Long> roleIds = userRoles.stream().map(item -> item.getRId()).collect(Collectors.toList());
        ret.put("roles", roles);
        ret.put("userOwns", roleIds);
        return CommonResult.success(ret);
    }

    @ApiOperation(value = "获取用户应用")
    @RequestMapping(value = "/appList", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult<Map<String,Object>> appList(@RequestBody SysUser user) {
        Map<String,Object> ret = new HashMap<>();
        List<SysApp> apps = appService.findAll();
        List<SysUserApp> userApps = userAppService.findUserAppsByUserId(user.getId());
        List<Long> appIds = userApps.stream().map(item -> item.getAppId()).collect(Collectors.toList());
        ret.put("apps", apps);
        ret.put("userOwns", appIds);
        return CommonResult.success(ret);
    }

    @ApiOperation(value = "更新用户应用")
    @RequestMapping(value = "/appUpdate", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public CommonResult appUpdate(@RequestBody SysUser user) {
        userAppService.deleteUserAPpByUserId(user.getId());
        List<SysUserApp> list = new ArrayList<>();
        for(String appId : user.getApps()){
            SysUserApp userApp = new SysUserApp();
            userApp.setId(userAppService.createId(userApp));
            userApp.setUId(user.getId());
            userApp.setAppId(Long.parseLong(appId));
            userApp.setCreateTime(new Date());
            userApp.setUpdateTime(new Date());
            list.add(userApp);
        }
        userAppService.saveAll(list);
        return CommonResult.success();
    }

}
